package org.chen.ctrip.service.translate.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

@Service
@Slf4j
public class BaiduTranslationService {

    private final RestTemplate restTemplate;

    @Value("${baidu.translate.app-id:}")
    private String appId;

    @Value("${baidu.translate.secret-key:}")
    private String secretKey;

    private final Random random;

    private static final String BAIDU_TRANSLATE_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    public BaiduTranslationService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        this.random = new Random();
    }

    /**
     * 使用百度翻译API进行翻译
     * @param text 要翻译的文本
     * @param from 源语言
     * @param to 目标语言
     * @return 翻译结果
     */
    public String translate(String text, String from, String to) {
        if (text == null || text.trim().isEmpty()) {
            return "";
        }

        try {
            // 生成随机数
            String salt = generateSalt();
            
            // 生成签名
            String sign = generateSign(appId, text, salt, secretKey);
            
            // 构建请求URL
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.set("User-Agent", "Mozilla/5.0 (Java BaiduTranslate Client)");

            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            formData.add("q", text);              // RestTemplate会自动处理编码
            formData.add("from", from);
            formData.add("to", to);
            formData.add("appid", appId);
            formData.add("salt", salt);
            formData.add("sign", sign);

            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, headers);

            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(BAIDU_TRANSLATE_URL, entity, String.class);
            
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                return parseTranslationResponse(response.getBody());
            } else {
                throw new RuntimeException("百度翻译API调用失败");
            }

        } catch (Exception e) {
            log.error("百度翻译失败: {}", e.getMessage(), e);
            throw new RuntimeException("百度翻译失败: " + e.getMessage());
        }
    }

    /**
     * 生成随机salt（5位数字）
     */
    private String generateSalt() {
        StringBuilder salt = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            salt.append(random.nextInt(10));
        }
        return salt.toString();
    }

    /**
     * 生成MD5签名
     * 签名规则：appid + q + salt + appkey 的MD5值
     * 注意：q参数不进行URL编码
     */
    private String generateSign(String appid, String q, String salt, String appkey) {
        try {
            // 关键：签名生成时q参数不进行URL编码
            String signStr = appid + q + salt + appkey;
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(signStr.getBytes(StandardCharsets.UTF_8));

            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不可用", e);
        }
    }

    /**
     * 解析百度翻译API响应
     */
    private String parseTranslationResponse(String responseBody) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(responseBody);
            
            // 检查是否有错误
            if (rootNode.has("error_code")) {
                String errorCode = rootNode.get("error_code").asText();
                String errorMsg = rootNode.has("error_msg") ? rootNode.get("error_msg").asText() : "未知错误";
                throw new RuntimeException("百度翻译错误: " + errorCode + " - " + errorMsg);
            }
            
            // 获取翻译结果
            JsonNode transResult = rootNode.get("trans_result");
            if (transResult != null && transResult.isArray() && !transResult.isEmpty()) {
                StringBuilder result = new StringBuilder();
                for (JsonNode item : transResult) {
                    if (item.has("dst")) {
                        if (!result.isEmpty()) {
                            result.append("\n");
                        }
                        result.append(item.get("dst").asText());
                    }
                }
                return result.toString();
            }
            
            throw new RuntimeException("无法解析翻译结果");
            
        } catch (Exception e) {
            log.error("解析百度翻译响应失败: {}", e.getMessage());
            throw new RuntimeException("解析翻译响应失败: " + e.getMessage());
        }
    }
}